window.onload = function () {
    render();

}

function render() {
    renderTitle();
    renderCommon();
    renderProbeData();
    renderAlarm();
    renderAttributeData();
}

/**
 * 渲染标题头部
 */
function renderTitle() {
    document.getElementsByClassName("filename")[0].textContent = reportData.title;
    document.getElementsByClassName("createdtime")[0].textContent = moment(reportData.createTime).format("YYYY-MM-DD HH:mm:ss");
}

function renderCommon() {
    /**
     * Waybill
     */
    if (reportData.wayBill) {
        var wayBillDom = document.getElementsByClassName("Waybill")[0];
        var infoArray = wayBillDom.getElementsByClassName("td");

        //运单编码
        infoArray[0].getElementsByTagName("div")[1].textContent = reportData.wayBill.waybillNumber || "";
        //快递单号
        infoArray[1].getElementsByTagName("div")[1].textContent = reportData.wayBill.expressNumber || "";
        //货物名称
        infoArray[2].getElementsByTagName("div")[1].textContent = reportData.wayBill.goodsName || "";
        //订单编号
        infoArray[3].getElementsByTagName("div")[1].textContent = reportData.wayBill.order || "";
        //内容描述
        infoArray[4].getElementsByTagName("div")[1].textContent = reportData.wayBill.description || "暂无";
        //冷藏箱编号
        infoArray[5].getElementsByTagName("div")[1].textContent = reportData.wayBill.coolerCode || "";
        //开始时间
        infoArray[6].getElementsByTagName("div")[1].textContent = reportData.wayBill.startTime || "";
        //发货方
        infoArray[7].getElementsByTagName("div")[1].textContent = reportData.wayBill.sender || "";
        //结束时间
        infoArray[8].getElementsByTagName("div")[1].textContent = reportData.wayBill.endTime || "";
        //收货方
        infoArray[9].getElementsByTagName("div")[1].textContent = reportData.wayBill.receiver || "";

    } else {
        //隐藏运单信息
        unShow("Waybill");
    }

    /**
     * deviceInfo
     */
    if (reportData.deviceInfo) {
        var deviceInfoDom = document.getElementsByClassName("deviceInfo")[0];
        var infoArray = deviceInfoDom.getElementsByClassName("td");
        //名称
        infoArray[0].getElementsByTagName("div")[1].textContent = reportData.deviceInfo.deviceName;
        //类型
        infoArray[1].getElementsByTagName("div")[1].textContent = reportData.deviceInfo.typeName;
        //guid
        infoArray[2].getElementsByTagName("div")[1].textContent = reportData.deviceInfo.deviceGuid;
        //subid
        // infoArray[1].getElementsByTagName("div")[1].textContent = reportData.deviceInfo.subUid;
    }

    if (reportData.configurationInfo) {

        var configurationInfoDom = document.getElementsByClassName("configurationInfo")[0];
        var infoArray = configurationInfoDom.getElementsByClassName("td");
        //记录间隔
        infoArray[0].getElementsByTagName("div")[1].textContent = reportData.configurationInfo.log;

        //上传间隔
        infoArray[1].getElementsByTagName("div")[1].textContent = reportData.configurationInfo.report;

        //时区
        infoArray[2].getElementsByTagName("div")[1].textContent = reportData.configurationInfo.timeZone;

    }

}

/**
 * 渲染告警
 */
function renderAlarm() {
    $('.alarm table tbody').eq(1).empty();

    for (var index = 0, len = reportData.alarmInfo.length; index < len; index++) {
        var line = document.createElement("tr");
        var alarm = reportData.alarmInfo[index];

        $(line).append(fixWithTDRow(alarm.alarmInfo));
        $(line).append(fixWithTDRow(alarm.alarmTime));
        $(line).append(fixWithTDRow(alarm.alarmTimes));
        $(line).append(fixWithTDRow(alarm.status ? "告警" : "解除"));

        $('.alarm table tbody').eq(1).append(line);

    }
    if (reportData.exportAlarm) {
        var boolean = true;

        var pageIndex = 0;
        var tableHeight = $('.alarmdataList .head').height();//预留的高度
        $.each(reportData.alarmDataList, function (index, a) {

            //添加数据行之前判断当前table高度 如果接近 768px 则另开一页
            var nowH = $('.alarmdataList table').eq(pageIndex).height();
            if (nowH > ($('.page').height() - tableHeight - 50)) {

                //另开一个table 复制当前表头
                var head = $('.alarmdataList table').eq(pageIndex).find('tbody tr').eq(0).prop("outerHTML");


                $('.alarmdataList').append('<div class="page"><table border="1"><tbody></tbody></table></div>')
                pageIndex++;

                $('.alarmdataList table').eq(pageIndex).find('tbody').append(head);

            }

            var line = document.createElement("tr");
            var alarmDataAttribute = reportData.alarmDataList[index];

            $(line).append(fixWithTDRow(alarmDataAttribute.alarmTimeStr));
            $(line).append(fixWithTDRow(alarmDataAttribute.alarmName));
            $(line).append(fixWithTDRow(alarmDataAttribute.alarmMessage));
            $(line).append(fixWithTDRow(alarmDataAttribute.alarmState == 1 ? '告警' : '解除'));

            if (alarmDataAttribute.alarmState == 1 && boolean) {
                //如果有告警没解除
                $('.pic.ok').css("display", 'none');
                $('.pic.alarm').css("display", 'flex');
                $('.pic.alarm').css("display", '-webkit-flex');
                boolean = false;
            }

            $('.alarmdataList table').eq(pageIndex).find('tbody').eq(0).append(line);
        })

        if(reportData.exportAlarm && reportData.exportAlarm.length > 0){
            $('.alarmdataList').css('margin-top',"-0.5cm")
        }
        
    } else {
        unShow("alarmdataList");
    }
}

/**
 * 渲染图表
 */
function renderProbeData() {

    var tr = $('.dataList table tbody').eq(0).find('tr');

    //表头
    tr.empty();
    tr.append('<th class="rowspan-cell">记录时间</th>');

    for (var index = 0, len = reportData.probeData.length; index < len; index++) {


        var probeData = reportData.probeData[index];
        probeData["title"] = probeData.name + "统计信息";

        tr.append("<th>" + probeData.name + "</th>");

        var data = [];

        var maxValue = 0;
        var minValue = 0;
        var average = 0;
        var total = 0;

        var xData = [];


        var temp = 0;

        $.each(reportData.probeDataAttribute, function (i, rdata) {
            xData.push(moment(rdata.monitorTimeStr).format('YYYY/MM/DD HH:mm:ss'));
            $.each(rdata.paramDataModelList, function (j, pdata) {
                if (pdata.paramValue) {
                    if (isNumber(pdata.paramValue)) {
                        pdata.paramValue = parseFloat(pdata.paramValue);
                        if (pdata.paramId == probeData.id) {
                            if (i == 0) {
                                //第一次遍历赋值
                                maxValue = pdata.paramValue;
                                minValue = pdata.paramValue;
                            }
                            if (pdata.paramValue > maxValue) {
                                maxValue = pdata.paramValue;
                            }
                            if (pdata.paramValue < minValue) {
                                minValue = pdata.paramValue;
                            }
                            data.push(pdata.paramValue);
                            total += pdata.paramValue;
                            var e = Math.exp(-10000 / (pdata.paramValue + 273.1));
                            temp += e;
                        }
                    }
                }

            })
        });

        if (data.length == 0) {

            probeData.maxValue = "";
            probeData.minValue = '';
            probeData.average = '';
        } else {

            var result = (-10000 / Math.log(temp / data.length)) - 273.1;

            average = total / data.length;

            probeData.maxValue = parseFloat(maxValue);
            probeData.minValue = parseFloat(minValue);
            probeData.average = average;

            if (probeData.unitCode == '℃' || probeData.unitCode == '℉') {
                probeData.averageTem = result;
            }

        }


        var html = getChartsDom(probeData);
        $('.probeData').eq(0).append(html);
        renderEcharts(document.getElementsByClassName("chart")[index], probeData, data, xData);
    }

    if (reportData.exportGeoPosition) {
        // tr.append('<th class="rowspan-cell" rowspan="' + len + '">经度</th>');
        // tr.append('<th class="rowspan-cell" rowspan="' + len + '">纬度</th>');
        tr.append('<th class="rowspan-cell" rowspan="' + len + '">地址</th>');
    }

    if (reportData.exportRemark) {
        tr.append('<th class="rowspan-cell" rowspan="' + len + '">备注</th>');
    }
}

/**
 * 渲染时序数据
 */
function renderAttributeData() {

    if (!reportData.exportDataList) {
        unShow("dataList");
        return;
    }

    $('.dataList table tbody').eq(1).empty();

    var page1 = $('.dataList .page').eq(0);
    page1.css("height", (page1.height() - $('.dataList .head').height()) + "px")

    var pageIndex = 0;
    var tableHeight = $('.dataList .head').height();//预留的高度
    for (var index = 0, len = reportData.probeDataAttribute.length; index < len; index++) {

        //添加数据行之前判断当前table高度 如果接近 768px 则另开一页
        var nowH = $('.dataList table').eq(pageIndex).height();
        if (nowH > ($('.page').height() - tableHeight - 50)) {

            //另开一个table 复制当前表头
            var head = $('.dataList table').eq(pageIndex).find('tbody').eq(0).prop("outerHTML");

            $('.dataList').append('<div class="page"><table border="1"></table></div>')
            pageIndex++;

            $('.dataList table').eq(pageIndex).append(head);
            $('.dataList table').eq(pageIndex).append('<tbody></tbody>');

        }

        var probeDataAttribute = reportData.probeDataAttribute[index];

        var line = document.createElement("tr");

        $(line).append(fixWithTD(probeDataAttribute.monitorTimeStr));

        for (var p = 0, plen = reportData.probeData.length; p < plen; p++) {
            for (var i = 0, ilen = probeDataAttribute.paramDataModelList.length; i < ilen; i++) {

                if (probeDataAttribute.paramDataModelList[i].paramId == reportData.probeData[p].id) {
                    
                    var paramDataModel = probeDataAttribute.paramDataModelList[i];
                    $(line).append(fixWithTD(paramDataModel.paramValue + paramDataModel.unitCode));

                    break;
                }


            }
        }

        if (reportData.exportGeoPosition) {
            // $(line).append(fixWithTD(probeDataAttribute.longitude || "", ilen));
            // $(line).append(fixWithTD(probeDataAttribute.latitude || "", ilen));
            $(line).append(fixWithTDRowAddress(probeDataAttribute.address || ""));

        }

        if (reportData.exportRemark) {
            $(line).append(fixWithTD(probeDataAttribute.remark || ""));
        }
        $('.dataList table').eq(pageIndex).find('tbody').eq(1).append(line);




    }

    if(reportData.showPage){
        var pageCount = $('.page').length;

        for (var i = 0; i < pageCount; i++) {
            $('.page').eq(i).append('<p class="pageIndex">' + (i + 1) + '/' + pageCount + '</p>')
        }
    }

    var lastpage = $('.dataList .page:last').height();

    var lasttable = $('.dataList table:last').height();

    if (lasttable < lastpage - 50) {
        $('.dataList .page:last').height(lasttable + 50)
    }

}

function fixWithTDRow(data) {
    return '<td>' + data + '</td>';
}

function fixWithTDRowAddress(data) {
    return '<td class="rowspan-cell addressTD">' + data + '</td>';
}

function fixWithTD(data, rowspan) {
    if (!rowspan) {
        return '<td class="rowspan-cell">' + data + '</td>';
    }
    return '<td class="rowspan-cell" rowspan = "' + rowspan + '">' + data + "</td>";
}

function renderEcharts(dom, probeData, data, xData) {
    var myChart = echarts.init(dom);

    var maxValue;
    var minValue;

    var markData = [
    ]
    if (probeData.upperLimit) {
        markData.push(
            {
                yAxis: probeData.upperLimit
            }
        )
        maxValue = probeData.maxValue > probeData.upperLimit ? probeData.maxValue : probeData.upperLimit;
    } else {
        maxValue = probeData.maxValue;
    }

    if (probeData.lowerLimit) {
        markData.push(
            {
                yAxis: probeData.lowerLimit
            }
        )
        minValue = probeData.minValue < probeData.lowerLimit ? probeData.minValue : probeData.lowerLimit;
    } else {
        minValue = probeData.minValue
    }

    // 指定图表的配置项和数据
    var option = {
        color: ['#1979C9', '#D62A0D', '#D62A0D'],
        grid: {
            left: 30,
            right: 30
        },
        legend: {
            type: 'plain',
            data: [probeData.name, '探头上限', '探头下限']
        },
        xAxis: {
            type: 'category',
            name: '记录时间',
            nameLocation: 'center',
            nameGap: 50,
            boundaryGap: false,
            nameTextStyle: {
                fontSize: 10,
                fontWeight: 'bold',
            },
            splitLine: {
                show: true
            },
            data: xData,
            axisLabel: {
                interval: parseInt(xData.length / 7),
                fontSize: 10,
                color: '#1d1f1d',
                // rotate: 45,
                showMaxLabel: true,
                showMinLabel: true,
                formatter: function (value) {
                    var d = value.split(' ');
                    return d[0] + '\n' + d[1];
                }
            }
        },
        yAxis: {
            max: maxValue,
            min: minValue,
            type: 'value',
            name: probeData.unitCode,
            nameLocation: 'end',
            nameGap: 30,
            nameTextStyle: {
                fontSize: 10,
                fontWeight: 'bold',
            },
            splitLine: {
                show: true
            }
        },
        series: [{
            name: probeData.name,
            data: data,
            type: 'line',
            symbol: 'none',
            yAxisIndex: 0,
            lineStyle: {
                color: '#1979C9'
            },
            markLine: {
                symbol: 'none',
                label: {
                    position: "end"
                },
                lineStyle: {
                    color: '#D62A0D',
                    type: 'dashed',
                    width: 2
                },
                data: markData
            }
        },
        {
            name: '探头上限',
            data: [],
            type: 'line',
            symbol: 'none',
            yAxisIndex: 0

        },
        {
            name: '探头下限',
            data: [],
            type: 'line',
            symbol: 'none',
            yAxisIndex: 0
        }]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    myChart.resize();


}

/**
 * 通过class隐藏标签
 * @param {样式class} classname 
 */
function unShow(classname) {
    document.getElementsByClassName(classname)[0].style.display = 'none'
}

function getChartsDom(data) {

    if (!data) {
        return;
    }
    var startTime = "";
    var endTime = "";
    if (reportData.probeDataAttribute.length > 0) {
        startTime = reportData.probeDataAttribute[reportData.probeDataAttribute.length - 1].monitorTimeStr;
        endTime = reportData.probeDataAttribute[0].monitorTimeStr;
    }

    var average = '';
    if (data.average || data.average == 0) {
        if ("" != data.average)
            average = parseFloat(data.average).toFixed(4) + data.unitCode;
    }

    var averageTem = '';
    if (data.averageTem || data.averageTem == 0) {
        if ("" != data.averageTem)
            averageTem = parseFloat(data.averageTem).toFixed(4) + data.unitCode;
    }

    var html = '<div class="common probeData page"><div class="box head">${data.title}</div><div class="box table"><div class="td"><div>最大值：</div><div>${data.maxValue}</div></div><div class="td"><div>开启时间：</div><div>${data.startTime}</div></div></div><div class="box table"><div class="td"><div>最小值：</div><div>${data.minValue}</div></div><div class="td"><div>停止时间：</div><div>${data.endTime}</div></div></div><div class="box table"><div class="td"><div>平均值：</div><div>${data.average}</div></div><div class="td"><div>记录时长：</div><div>${data.time}</div></div></div><div class="box table"><div class="td"><div>上限要求：</div><div>${data.upperLimit}</div></div><div class="td"><div>平均动力学温度：</div><div>${data.averageTem}</div></div></div><div class="box table"><div class="td"><div>下限要求：</div><div>${data.lowerLimit}</div></div><div class="td"><div>记录条数：</div><div>${data.dataCount}</div></div></div><div class="chart"></div></div>';
    html = html.replace("${data.title}", data.title)
        .replace("${data.upperLimit}", (data.upperLimit || data.upperLimit == 0) ? (data.upperLimit + data.unitCode) : "")
        .replace("${data.startTime}", startTime || "")
        .replace("${data.lowerLimit}", (data.lowerLimit || data.lowerLimit == 0) ? (data.lowerLimit + data.unitCode) : "")
        .replace("${data.endTime}", endTime || '')
        .replace("${data.maxValue}", (data.maxValue || data.maxValue == 0) ? (data.maxValue + data.unitCode) : '')
        .replace("${data.dataCount}", reportData.probeDataAttribute.length)
        .replace("${data.minValue}", (data.minValue || data.minValue == 0) ? (data.minValue + data.unitCode) : '')
        .replace("${data.average}", average)
        .replace("${data.averageTem}", averageTem)
        .replace("${data.time}", reportData.logTime);

    return html;

}


function isNumber(val) {

    return /^[+-]?\d+(\.\d+)?$/.test(val)

}
